package com.siyuanren.gcocp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.siyuanren.gcocp.dto.PartDTO;
import com.siyuanren.gcocp.dto.PartDetailDTO;
import com.siyuanren.gcocp.entity.Part;
import com.siyuanren.gcocp.entity.PartExample;
import com.siyuanren.gcocp.entity.Word;
import com.siyuanren.gcocp.entity.WordExample;
import com.siyuanren.gcocp.mapper.WordExtMapper;
import com.siyuanren.gcocp.mapper.base.PartMapper;
import com.siyuanren.gcocp.service.WordService;
import com.siyuanren.gcocp.vo.QueryPartListVO;
import com.siyuanren.gcocp.vo.QueryPartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by   anxing
 * Project_name enword-java
 * Path         com.siyuanren.gcocp.service
 * Date         2018/7/24
 * Time         17:23
 * Description
 */
@Slf4j
@Service
public class WordServiceImpl implements WordService {
    @Autowired
    PartMapper partMapper;
    @Autowired
    WordExtMapper wordMapper;

    @Override
    public PartDetailDTO getPartDetail(QueryPartVO vo) {
        Part part = partMapper.selectByPrimaryKey(vo.getPartId());
        WordExample example = new WordExample();
        example.or().andMainPartIdEqualTo(vo.getPartId());
        List<Word> words = wordMapper.selectByExample(example);
        List<Word> relateWords = wordMapper.getRelateWord(vo.getPartId());

        PartDetailDTO detailDTO = new PartDetailDTO();
        BeanUtils.copyProperties(part, detailDTO);
        detailDTO.setWords(words);
        detailDTO.setExtraWords(relateWords);
        return detailDTO;
    }

    @Override
    public List<PartDTO> getPartList(QueryPartListVO vo) {
        PageHelper.startPage(vo.getPageNum() + 1, vo.getPageSize());
        PartExample examPart = new PartExample();

        List<Part> parts = partMapper.selectByExample(examPart);
        List<PartDTO> dtos = new ArrayList<>();
        for (Part part : parts) {
            PartDTO dto = new PartDTO();
            BeanUtils.copyProperties(part, dto);

            WordExample example = new WordExample();
            example.or().andMainPartIdEqualTo(part.getId());
            List<Word> words = wordMapper.selectByExample(example);
            if (words.size() > 0) {
                dto.setWord(words.get(0).getWord());
                dto.setWordTrans(words.get(0).getWordTranslate());
            }

            dtos.add(dto);
        }
        return dtos;
    }
}
